package com.example.demo.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.example.demo.exception.BusinessException;
import com.example.demo.mapper.UserMapper;
import com.example.demo.pojo.RegisterRequest;
import com.example.demo.pojo.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author admin
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public List<User> getUserById(String id) {
        List<User> userById = new ArrayList<>();
        User userById1 = userMapper.getUserById(id);
        if (userById1 != null) {
            userById.add(userById1);
        }else {
            userById = List.of();
        }
        return userById;
    }

    @Override
    public List<User> getAllUser(RegisterRequest request) {
        List<User> allUsers = userMapper.getAllUsers(request);
        return allUsers;
    }


    @Transactional
    @Override
    public int updateById(User user) {
        user.setUpdateTime(DateUtil.date());
        User userById = userMapper.getUserById(user.getId().toString());
        if(userById.getCreateTime() == null || userById.getUpdateTime() == null){
            user.setCreateTime(DateUtil.date());
            user.setUpdateTime(DateUtil.date());
        }
        int num = userMapper.updateUser(user);
        return num;
    }

    @Transactional
    @Override
    public int insertUser(User user) {
        user.setRegistrationDate(DateUtil.date());
        user.setCreateTime(DateUtil.date());
        int num = userMapper.insert(user);
        return num;
    }

    @Transactional
    @Override
    public int deleteUser(User user) {
        Map<String,Object> map = new HashMap<>();
        map.put("id",user.getId().toString());
        User userBySelect = userMapper.selectUser(map);
        if(userBySelect == null){
            throw new BusinessException(500,"当前用户系统不存在");
        }
        int num = userMapper.deleteById(user.getId().toString());
        return num;
    }
}
